package com.example.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.example.pojo.IZlyJSONResult;

@ControllerAdvice
public class IZlyExceptionHandler {
	
	public static final String ZLY_ERROR_VIEW ="error";
	
//	@ExceptionHandler(value=Exception.class)
	/*public Object errorHandler(HttpServletRequest request,HttpServletResponse response,Exception e) throws Exception{
		
		e.printStackTrace();
		
		ModelAndView modeView = new ModelAndView();
		modeView.addObject("exception",e);
		modeView.addObject("url",request.getRequestURI());
		modeView.setViewName(ZLY_ERROR_VIEW);
		return modeView;
	}*/
	
	@ExceptionHandler(value = Exception.class)
    public Object errorHandler(HttpServletRequest reqest, 
    		HttpServletResponse response, Exception e) throws Exception {
    	
    	e.printStackTrace();
    	//判断是否是ajax请求
    	if (isAjax(reqest)) {
    		return IZlyJSONResult.errorException(e.getMessage());
    	} else {
    		ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", reqest.getRequestURL());
            mav.setViewName(ZLY_ERROR_VIEW);
            return mav;
    	}
    }
	
	/**
	 * @Title: IMoocExceptionHandler.java
	 * @Package com.imooc.exception
	 * @Description: 判断是否是ajax请求
	 */
	public static boolean isAjax(HttpServletRequest httpRequest){
		return  (httpRequest.getHeader("X-Requested-With") != null  
					&& "XMLHttpRequest"
						.equals( httpRequest.getHeader("X-Requested-With").toString()) );
	}
}
